/**
 * 获取图片主题颜色
 * @param path 图片的路径
 * @param canvasId 画布id
 * @param success 获取图片颜色成功回调，主题色的RGB颜色值
 * @param fail 获取图片颜色失败回调
 */
export const getImageThemeColor = (that, path, canvasId, success = () => {}, fail = () => {}) => {
  // #ifdef H5
  // H5环境下使用原有逻辑
  uni.getImageInfo({
    src: path,
    success: (e) => {
      const ctx = uni.createCanvasContext(canvasId, that);
      const imgWidth = 300;
      const imgHeight = 150;
      ctx.drawImage(e.path, 0, 0, imgWidth, imgHeight);
      ctx.save();
      ctx.draw(true, () => {
        uni.canvasGetImageData({
          canvasId: canvasId,
          x: 0,
          y: 0,
          width: imgWidth,
          height: imgHeight,
          fail: fail,
          success(res) {
            let data = res.data;
            
            // 使用改进的采样算法
            const dominantColor = extractDominantColor(data, imgWidth, imgHeight);
            
            success(dominantColor);
          },
        }, that);
      });
    }
  })
  // #endif
  
  // #ifndef H5

  // 先检查图片是否是网络图片，如果是网络图片，需要先下载
  if (path.startsWith('http://') || path.startsWith('https://')) {
    uni.downloadFile({
      url: path,
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('图片下载成功:', res.tempFilePath);
          processLocalImage(res.tempFilePath);
        } else {
          console.error('图片下载失败，状态码:', res.statusCode);
          fail && fail();
        }
      },
      fail: (error) => {
        console.error('图片下载失败:', error);
        // 尝试直接使用原始路径
        processLocalImage(path);
      }
    });
  } else {
    // 本地图片直接处理
    processLocalImage(path);
  }
  
  function processLocalImage(localPath) {

    // 使用新的API uni.createCanvasContext 替代旧API
    const ctx = uni.createCanvasContext(canvasId, that);
    
    // 设置更小的尺寸以提高性能
    const imgWidth = 50; // 进一步减小尺寸
    const imgHeight = 50;
    
    // 先清空画布
    ctx.clearRect(0, 0, imgWidth, imgHeight);
    
    // 绘制图片
    ctx.drawImage(localPath, 0, 0, imgWidth, imgHeight);
   
    // 使用draw方法并等待回调
    ctx.draw(false, () => {
   
      // 延迟一下确保绘制完成
      setTimeout(() => {
        uni.canvasGetImageData({
          canvasId: canvasId,
          x: 0,
          y: 0,
          width: imgWidth,
          height: imgHeight,
          success: (res) => {
   
            try {
              const data = res.data;
              if (!data || data.length === 0) {
                console.warn('获取图片数据失败');
                fail && fail();
                return;
              }
              
              // 使用改进的采样算法
              const dominantColor = extractDominantColor(data, imgWidth, imgHeight);
              
              // 增强颜色饱和度，使背景色更鲜艳
              let [r, g, b] = dominantColor.split(',').map(Number);
              
              const max = Math.max(r, g, b);
              const min = Math.min(r, g, b);
              const delta = max - min;
              
              if (delta > 0) {
                const saturation = delta / max;
                const factor = Math.min(1.5, 0.7 + saturation * 0.8); // 增强饱和度
                
                r = Math.min(255, Math.floor(r * factor));
                g = Math.min(255, Math.floor(g * factor));
                b = Math.min(255, Math.floor(b * factor));
              }
              
              success([r, g, b].join(','));
            } catch (error) {
              console.error('处理图片数据出错:', error);
              fail && fail();
            }
          },
          fail: (error) => {
            console.error('获取画布数据失败:', error);
            fail && fail();
          }
        }, that);
      }, 100); // 减少延迟时间到100ms
    });
  }
  // #endif
}

/**
 * 提取图片主要颜色的改进算法
 * @param {Array} imageData 图片像素数据
 * @param {number} width 图片宽度
 * @param {number} height 图片高度
 * @returns {string} RGB颜色字符串
 */
function extractDominantColor(imageData, width, height) {
  // 创建颜色映射，用于统计颜色频率
  const colorMap = {};
  const totalPixels = width * height;
  
  // 采样步长，根据图片大小动态调整
  const sampleSize = Math.min(1000, totalPixels); // 最多采样1000个像素
  const step = Math.max(1, Math.floor(totalPixels / sampleSize));
  
  // 采样并统计颜色
  for (let i = 0; i < imageData.length; i += 4 * step) {
    const r = imageData[i];
    const g = imageData[i + 1];
    const b = imageData[i + 2];
    const a = imageData[i + 3];
    
    // 跳过透明度过低的像素
    if (a < 128) continue;
    
    // 将颜色量化到较低的精度，以便合并相似颜色
    const quantizedR = Math.floor(r / 16) * 16;
    const quantizedG = Math.floor(g / 16) * 16;
    const quantizedB = Math.floor(b / 16) * 16;
    
    const colorKey = `${quantizedR},${quantizedG},${quantizedB}`;
    
    if (!colorMap[colorKey]) {
      colorMap[colorKey] = {
        count: 0,
        r: 0,
        g: 0,
        b: 0
      };
    }
    
    colorMap[colorKey].count++;
    colorMap[colorKey].r += r;
    colorMap[colorKey].g += g;
    colorMap[colorKey].b += b;
  }
  
  // 找出出现频率最高的颜色
  let maxCount = 0;
  let dominantColor = '128,128,128'; // 默认灰色
  
  for (const colorKey in colorMap) {
    const colorData = colorMap[colorKey];
    
    // 计算该颜色的实际平均值
    const avgR = Math.round(colorData.r / colorData.count);
    const avgG = Math.round(colorData.g / colorData.count);
    const avgB = Math.round(colorData.b / colorData.count);
    
    // 根据颜色权重和饱和度进行评分
    const saturation = Math.max(avgR, avgG, avgB) - Math.min(avgR, avgG, avgB);
    const weightedScore = colorData.count * (1 + saturation / 255);
    
    if (weightedScore > maxCount) {
      maxCount = weightedScore;
      dominantColor = `${avgR},${avgG},${avgB}`;
    }
  }
  
  return dominantColor;
}